from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.departments.models import Department


class User(models.Model):
    """
    用户表：存储用户的基本信息
    """
    class Status(models.TextChoices):
        ACTIVE = 'active', _('Active')
        INACTIVE = 'inactive', _('Inactive')

    user_id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=50, unique=True, verbose_name=_("Username"))
    email = models.EmailField(max_length=100, unique=True, verbose_name=_("Email"))
    password_hash = models.CharField(max_length=255, verbose_name=_("Password Hash"))
    employee_number = models.CharField(max_length=20, unique=True, verbose_name=_("Employee Number"))  # 工号
    department = models.ForeignKey(
        Department,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="users",
        verbose_name=_("Department")
    )
    status = models.CharField(
        max_length=10,
        choices=Status.choices,
        default=Status.ACTIVE,
        verbose_name=_("Status")
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created At"))
    updated_at = models.DateTimeField(auto_now=True, verbose_name=_("Updated At"))

    class Meta:
        db_table = "users"
        verbose_name = _("User")
        verbose_name_plural = _("Users")

    def __str__(self):
        return f"{self.username} ({self.employee_number})"


class UserRole(models.Model):
    """
    用户角色映射表：管理用户与角色之间的关系
    """
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="roles", verbose_name=_("User"))
    role_id = models.IntegerField(verbose_name=_("Role ID"))  # 角色 ID，独立管理角色
    assigned_by = models.IntegerField(verbose_name=_("Assigned By"))  # 分配该角色的管理员 ID
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created At"))

    class Meta:
        db_table = "user_roles"
        verbose_name = _("User Role Mapping")
        verbose_name_plural = _("User Role Mappings")

    def __str__(self):
        return f"User: {self.user.username}, Role ID: {self.role_id}"
